package com.lagou.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.List;

/**
 * @author yangpeng
 * @time 2020/4/21
 * @since 1.0.0
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private static final int LENGTH = 4;


    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;

        this.serializer = serializer;

    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("解码");
        int size = byteBuf.readableBytes();
        if (size > RpcDecoder.LENGTH) {
            byte[] bytes = getByteFromBuf(byteBuf);
            byte[] bytes1 = new byte[bytes.length-4];
            System.arraycopy(bytes,4,bytes1,0,bytes1.length);
            String s = new String(bytes1);
            if(s.contains("{")) {
                RpcRequest deserialize = serializer.deserialize(RpcRequest.class, bytes1);
                if (deserialize != null) {
                    list.add(deserialize);
                }
            }else{
                list.add(s);
            }
        }
    }

    public byte[] getByteFromBuf(ByteBuf buf) {
        int size = buf.readableBytes();
        byte[] bytes = new byte[size];
        buf.readBytes(bytes);
        return bytes;
    }

}
